package com.mem.barrier;

import java.util.HashSet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * @author fanhaibo_900
 * 2021年04月24日20:14:08
 * <p>
 * 内存屏障：http://ifeve.com/jmm-cookbook-mb/，https://www.cnblogs.com/chenyangyao/p/5269622.html
 * <p>
 * <p>
 * JMM: java memory barrier  java内存屏障
 */
public class MemoryBarrier2 {

    private static volatile int a = 0;
    private static volatile int b = 0;
    private static volatile int x = 0;
    private static volatile int y = 0;

    public static void main(String[] args) throws InterruptedException {
        HashSet<String> stringHashset = new HashSet<String>();
        ExecutorService es = Executors.newFixedThreadPool(20);
        for (int i = 0; i < 10000; i++) {
            a = 0;
            b = 0;
            x = 0;
            y = 0;
            es.submit(() -> {
                try {
                    Thread.sleep(1L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                b = 2;
                y = a;
            });

            es.submit(() -> {
                try {
                    Thread.sleep(1L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                a = 1;
                x = b;
            });
            String s = String.format("{x=%d ,y= %d}", x, y);
            stringHashset.add(s);
        }


        es.shutdown();

        System.out.println(String.join("-------", stringHashset));
    }
}

// result:  {x=2 ,y= 1}-------{x=2 ,y= 0}-------{x=0 ,y= 0}-------{x=0 ,y= 1}